<?php


require_once("functions.php");
$db = connect_db();

$out = get_header();

var_dump($_GET);
$id = $_GET['id'];
$action = $_GET['action'];
if ($action == 'edit' && is_numeric($id)) {
	$sql = "select extra_variable, variable from fields where id = $id";
	$res = mysql_query($sql, $db);
	if($res === FALSE)
		die ("Row not found");
	$row = mysql_fetch_array($res);
	if ($row === FALSE) 
		die ("Row not found");

	$evar = $row['extra_variable'];
	$var = $row['variable'];
} else if ($action == 'update' && isset($_GET['variable'])) {
	$evar = isset($_GET['e_variable']) ?mysql_real_escape_string($_GET['e_variable']): '';
	$var = mysql_real_escape_string($_GET['variable']);
	if (is_numeric($id)){
		$sql1 = "select count(*) from fields where variable='$var' and extra_variable='$evar' and id<>$id";
		$sql = "update fields set variable='$var', extra_variable='$evar'  where id=$id";
	} else {
		$sql1 = "select count(*) from fields where variable='$var' and extra_variable='$evar'";
		$sql = "insert into fields (variable, extra_variable) values ('$var', '$evar')";
	}
	$res = mysql_query($sql1, $db);
	$cnt = mysql_result($res, 0,0);
	if ($cnt != 0)
		die ("value already exists");
	$res = mysql_query($sql, $db);
	header("Location: view_field.php");
} else if ($action == 'new') {
	$var = $evar = '';
}

$out .= "<h2>Add language</h2>\n";
$out .= '<form method="get" action="edit_field.php">'. "\n";
$out .= '<input type="hidden" name="id" value="' . $id  . "\"/>\n";
$out .= '<input type="hidden" name="action" value="update"/>' . "\n";
$out .= "Variable: <input type=\"text\" name=\"variable\" value=\"$var\"/>\n";
$out .= "Extra variable: <input type=\"text\" name=\"e_variable\" value=\"$evar\"/>\n";
$out .= "<br><input type=\"submit\" value=\"submit\" name=\"submit\"/>\n";
$out .= "</form>\n";


$out .= get_footer();


echo $out;


?>
